package com.angel.bo.admin.service.impl;

import com.angel.bo.admin.constants.AdminRestConstant;
import com.angel.bo.admin.constants.DictCodeConstant;
import com.angel.bo.admin.exception.AdminException;
import com.angel.bo.admin.mapper.UserMapper;
import com.angel.bo.admin.service.PermissionService;
import com.angel.bo.admin.service.UserRoleService;
import com.angel.bo.admin.service.UserService;
import com.angel.bo.auth.client.jwt.AuthUtil;
import com.angel.bo.beans.admin.dto.UserDto;
import com.angel.bo.beans.admin.entity.User;
import com.angel.bo.beans.admin.entity.UserRole;
import com.angel.bo.beans.admin.vo.UserVo;
import com.angel.bo.cache.annotation.DictParam;
import com.angel.bo.cache.annotation.ServiceCache;
import com.angel.bo.cache.annotation.TranslationDict;
import com.angel.bo.cache.constant.ServiceCacheActionEnum;
import com.angel.bo.cache.model.CacheType;
import com.angel.bo.common.msg.WebReturn;
import com.angel.bo.common.service.impl.BaseServiceImpl;
import com.angel.bo.common.vo.Query;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 16:02 2018/1/30
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends BaseServiceImpl<UserMapper,User> implements UserService{


    private BCryptPasswordEncoder encoder = new BCryptPasswordEncoder(12);


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthUtil authUtil;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PermissionService permissionService;

    /**
     * @param loginName
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description: 根据登录名获取用户信息
     * @Date: 15:55 2018/1/31
     */
    @Override
    public WebReturn<User> getUserInfoByLoginName(String loginName) {
        User example = new User();
        example.setLoginName(loginName);
        example.setState(DictCodeConstant.USER_STATE_CODE_1);
        User loginUser = this.selectOne(example);
        //查询用户是否有角色，没有角色返回空
        if(null != loginUser){
            UserRole userRole = new UserRole();
            userRole.setUserId(loginUser.getUserId());
            Long  count = userRoleService.selectCount(userRole);
            if(count == 0){
                return new WebReturn<>();
            }
        }

        return new WebReturn<>(loginUser);
    }

    @Override
    @ServiceCache(action = ServiceCacheActionEnum.ADD,scope = CacheType.USER_INFO,keyExpression = "#user.userId")
    public User selectOne(User user) {
        return super.selectOne(user);
    }

    @Override
    @ServiceCache(action = ServiceCacheActionEnum.EVICT,scope = CacheType.USER_INFO,keyExpression = "#user.userId")
    public void delete(User user) {
        super.delete(user);
    }

    @Override
    @ServiceCache(action = ServiceCacheActionEnum.EVICT,scope = CacheType.USER_INFO,keyExpression = "#user.userId")
    public void updateById(User user) {
        user.setPassword(encoder.encode(user.getPassword()));
        super.updateById(user);
    }

    @Override
    @ServiceCache(action = ServiceCacheActionEnum.EVICT,scope = CacheType.USER_INFO,keyExpression = "#user.userId")
    public void updateSelectiveById(User user) {
        if(null != user.getPassword()){
            user.setPassword(encoder.encode(user.getPassword()));
        }
        user.setModifyDate(new Date());
        super.updateSelectiveById(user);
    }

    /**
     * @param user
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description:
     * @Date: 16:20 2018/2/2
     */
    @Override
    @ServiceCache(action = ServiceCacheActionEnum.ADD,scope = CacheType.USER_INFO,keyExpression = "#user.loginName")
    public WebReturn saveUser(User user) {
        WebReturn response ;

        //查询用户是否唯一
        //复插入之前判断是否有重
        response = this.getUserInfoByLoginName(user.getLoginName());

        if(null != response.getData()){
            throw new AdminException(AdminRestConstant.ANGEL_ADMIN_ADDUSER_ERROR);
        }

        user.setCreateDate(new Date());
        user.setPassword(encoder.encode(user.getPassword()));
        user.setCreateUserId(authUtil.getUserIdFromToken());
        this.insert(user);
        response.setData(user);
        return response;
    }

    /**
     * 获取用户PAGE
     *
     * @param userVo
     * @return
     */
    @Override
    @TranslationDict({@DictParam(dictCode = "USER_GENDER_CODE",dictValueFiled = "gender",dictNameFiled = "genderName")})
    public WebReturn getUserPage(UserVo userVo) {
        WebReturn webReturn = new WebReturn();
        PageHelper.startPage(userVo.getPageNum(),userVo.getPageSize());
        List<UserDto> list = userMapper.getUserPage(userVo);
        PageInfo page = new PageInfo<>(list);
        webReturn.setData(page);
        return webReturn;
    }

    /**
     * 数据权限加载，项目启动时调用
     */
    @Override
    public void initPermissionData() {
        List<UserRole> userRoles = userRoleService.selectListAll();
        for (UserRole userRole : userRoles) {
            permissionService.initThePermissionDataByCurrentUser(userRole);
        }
    }

    @Override
    @TranslationDict({@DictParam(dictCode = "USER_GENDER_CODE",dictValueFiled = "gender",dictNameFiled = "genderName")})
    public WebReturn<User> selectByQuery(Query query) {
        return super.selectByQuery(query);
    }
}
